package com.boyou.sytzc.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.*
import com.boyou.sytzc.R
import com.boyou.sytzc.core.appctx.AppData
import com.boyou.sytzc.data.entity.RecordInfoEntity
import com.boyou.sytzc.databinding.ActivityRecordListBinding
import com.boyou.sytzc.core.adapter.RecordAdapter
import com.boyou.sytzc.utils.database.RecordDbHelper
import com.hi.dhl.binding.viewbind
import com.yuge.yugecse.ext.annotation.event.BackActionEvent
import com.yuge.yugecse.ext.uibasic.BasicActivity
import com.yuge.yugecse.util.device.ToastUtil
import com.yuge.yugecse.util.generic.ActivityUtil
import java.util.*

/**  记录列表页面   */
@BackActionEvent(isAllowDeal = true)
class RecordListActivity : BasicActivity(), AbsListView.OnScrollListener {

    private val binding by viewbind<ActivityRecordListBinding>()
    private val recordDbHelper by lazy { RecordDbHelper.getInstance(me) }//数据库辅助类
    private val recordAdapter by lazy { RecordAdapter(me) }//记录数据适配器
    private var modeType = -1//类型
    private var pageIndex = -1//当前页码
    private var isLastPage = false//是否是最后一页
    private var isLoading = false//是否正在加载数据

    private var handler: Handler = @SuppressLint("HandlerLeak")
    object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                MSG_GET_RECORD_INFOS_OK -> {
                    val infos = @Suppress("unchecked_cast") (msg.obj as ArrayList<RecordInfoEntity>)
                    recordAdapter.addItems(infos)
                    recordAdapter.notifyDataSetChanged()
                }
                MSG_GET_RECORD_INFOS_FAILED -> ToastUtil.showGenericToast(me, "获取记录数据失败!")
                MSG_GET_RECORD_LASTPAGE -> if (recordAdapter.count == 0 && pageIndex == -1)
                    ToastUtil.showGenericToast(this@RecordListActivity, "暂无数据!")
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(binding) {
            setSupportActionBar(binding.toolbar.apply { toolbar.title = "" })
            toolbar.setNavigationIcon(R.mipmap.ic_arrow_left_white)
            toolbar.setNavigationOnClickListener { ActivityUtil.goBack(me) }
            gvRecord.emptyView = binding.imgEmptyView
            gvRecord.adapter = recordAdapter
            gvRecord.setOnScrollListener(this@RecordListActivity)
            val data: Bundle? = intent?.extras
            if (data != null) modeType = data.getInt("type", -1)
            txtTitle.text =
                "记录列表(" + (if (modeType == -1) "全部" else if (modeType == 0) "装车模式" else "计时模式") + ")"
        }
        getAllRecordInfos(pageIndex + 1) //获取记录信息列表
    }

    override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {//列表停止了滑动
            if (binding.gvRecord.lastVisiblePosition == recordAdapter.count - 1) {
                getAllRecordInfos(pageIndex + 1)//获取记录信息列表
            }
        }
    }

    override fun onScroll(
        view: AbsListView,
        firstVisibleItem: Int,
        visibleItemCount: Int,
        totalItemCount: Int
    ) { }

    /**   获取记录信息列表    */
    private fun getAllRecordInfos(pageIndex: Int) {
        if (!isLoading && !isLastPage) {
            Thread {
                try {
                    isLoading = true//正在加载数据
                    val infos = recordDbHelper?.getAllRecordInfos(pageIndex);
                    if (infos != null && infos.size > 0) {
                        handler.obtainMessage(MSG_GET_RECORD_INFOS_OK, infos).sendToTarget()
                        isLastPage = infos.size < AppData.PAGE_SIZE
                        this@RecordListActivity.pageIndex = pageIndex//设置当前的页码
                    } else {
                        handler.obtainMessage(MSG_GET_RECORD_LASTPAGE).sendToTarget()
                        isLastPage = true//设为最后一页
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    handler.obtainMessage(MSG_GET_RECORD_INFOS_FAILED).sendToTarget()
                    isLastPage = true//设为最后一页
                }
                isLoading = false//加载完成
            }.start()
        }
    }

    companion object {

        const val MSG_GET_RECORD_INFOS_OK = 0x001//获取记录列表成功

        const val MSG_GET_RECORD_INFOS_FAILED = 0x002//获取记录列表失败

        const val MSG_GET_RECORD_LASTPAGE = 0x003//最后一页的记录

    }

}
